<?php
/**
 * Created by PhpStorm.
 * FileName: Appointment.class.php
 * User: Administrator
 * Date: 2018/4/16
 * Time: 10:02
 */

namespace Api\Controller;

use Org\Util\String;

class SMSController extends ApiController {

    public function __construct() {
        parent::__construct();
    }

    //获取短信验证码
    public function getEmsCode($mobile='', $len=6){
        $len = $len ? $len : I('len');
        $mobile = $mobile ? $mobile : I('mobile');
        if (!$this->isMobile($mobile)) {
            return $this->callBack('无效的手机号码！',$this->ERROR_CODE);
        }
        $tpl_id = '';
        $code = String::randString($len,1);
        $content = array('code' => $code);
        $rs = $this->sendSMS($mobile,$tpl_id,$content);
        $status = $rs['status'] ? 200 : 0;
        $message = $rs['status'] ? 'Success' : $rs['msg'];
        return $this->callBack($message, $status, $code);
    }

    /**
     * 发送短信通知
     * @param $mobile 手机号码
     * @param string $tpl_id 模板id
     * @param array $tpl_value 模板数据，一维数组格式
     * @return array
     */
    private function sendSMS($mobile,$tpl_id='',$tpl_value=array()){
        $rs = array('status' => false);
        $values = array();
        foreach ($tpl_value as $key => $value) {
            $values[] = sprintf('#%s#=%s',$key,$value);
        }
        $smsConf = array(
            'key'      => '9ab1e52c52ee8b8b51da74215e6b63ab',
            'mobile'    => $mobile,
            'tpl_id'    => $tpl_id,
            'tpl_value' => urlencode(implode('&',$values))
        );
        $url = 'http://v.juhe.cn/sms/send';
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 30);
        curl_setopt($curl, CURLOPT_TIMEOUT, 30);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($smsConf));
        curl_setopt($curl, CURLOPT_URL, $url);
        $response = curl_exec($curl);
        curl_close($curl);
        if($response){
            $result = json_decode($response,true);
            $error_code = $result['error_code'];
            if($error_code == 0){
                //状态为0，说明短信发送成功
                $rs['status'] = true;
                $rs['msg'] = '短信发送成功!';
            }else{
                //状态非0，说明失败
                $rs['msg'] = '短信发送失败('.$error_code.')：'.$result['reason'];
            }
        }else{
            //返回内容异常，以下可根据业务逻辑自行修改
            $rs['msg'] = '短信发送失败，请稍后再试';
        }
        return $rs;
    }

    /**
     * 验证手机号
     * @param string $mobile
     * @return boolean
     */
    private function isMobile($mobile='') {
        if (!preg_match('/^1[34578]{1}\d{9}$/',$mobile)){
            return false;
        }
        return true;
    }

}